package com.hzdaba.aiapi.service.impl;

import com.hzdaba.aiapi.domain.AiCustomer;
import com.hzdaba.aiapi.dto.CustomerLoginDto;
import com.hzdaba.aiapi.mapper.AiCustomerMapper;
import com.hzdaba.aiapi.properties.TokenKeyProperties;
import com.hzdaba.aiapi.service.AiCustomerService;
import com.hzdaba.aiapi.service.TokenService;
import com.hzdaba.aiapi.utils.PasswordUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Calendar;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;

@Service
public class AiCustomerServiceImpl implements AiCustomerService {

    /**
     * 访问用户数据
     */
    @Autowired
    private AiCustomerMapper aiCustomerMapper;

    /**
     * 处理 token 相关业务
     */
    @Autowired
    private TokenService tokenService;

    @Transactional(readOnly = true, timeout = 1)
    @Override
    public String login(CustomerLoginDto customerLoginDto) {
        AiCustomer aiCustomer = this.aiCustomerMapper.selectAiCustomerByUsername(customerLoginDto.getUsername());

        if (customerLoginDto == null) {
            return null;
        }

        if (!PasswordUtils.checkPassword(customerLoginDto.getPassword(), aiCustomer.getPassword())) {//密码错误
            return null;
        }

        if (!aiCustomer.getCode().equals(customerLoginDto.getCode())) {//租户编码不一致
            return null;
        }

        return this.tokenService.getToken(aiCustomer);
    }

}
